package com.qfedu.firstpage.controller;


import com.qfedu.firstpage.config.ApplicationHolder;
import com.qfedu.firstpage.config.cache.exception.ExceptionDict;
import com.qfedu.firstpage.config.cache.exception.SystemParams;
import com.qfedu.firstpage.config.cache.service.CacheService;
import com.qfedu.firstpage.entity.Buser;
import com.qfedu.firstpage.entity.ResponseData;
import com.qfedu.firstpage.service.UserService;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Instant;
import java.util.Date;
import java.util.HashMap;

/**
 * @author:
 * @date 2021/3/24 20:16
 */

@RestController
public class LoginController {

    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public ResponseData login2(HttpServletResponse response, HttpServletRequest request) {

        ResponseData bean = new ResponseData();

        // 获取请求的手机号
        String uphone = request.getParameter("uphone");
        // 获取请求的密码
        String password = request.getParameter("password");

        try {
            String password2 = userService.selectByPrimaryKey(uphone).getUpassword();
            // 获取用户状态，0 为普通用户，1 为会员
            int state = userService.selectByPrimaryKey(uphone).getUstate();
            // 获取用户id
            int uid = userService.selectByPrimaryKey(uphone).getUid();
            // 得到 用户名 密码
            if (password.equals(password2)) {

                //帐号信息是对的,直接给用户返回JWT相关的信息
                bean.setCode("1");

                bean.setMessage("登陆成功");

                Instant now = Instant.now();

                HashMap<Object, Object> map = new HashMap<>();

                // 产生token
                String jwt = Jwts.builder()

                        .setSubject("admin")//设置当前的用户是谁,当然任何信息都可以随便写,只不过你后续拿到之后不知道怎么处理而已
                        .setIssuedAt(Date.from(now))//设置开始的有效期
                        .setExpiration(Date.from(now.plusSeconds(3600)))//设置过期时间我当前时间顺眼一小时
                        .claim("uphone", uphone)
                        .claim("id", uid)//可以随便内容,主要是键值对,可以在需要的地方拿出来
                        .claim("quanxian", state)
                        .signWith(SignatureAlgorithm.HS256, "FireFly".getBytes())//设置签名的算法和秘钥值
                        .compact();
                System.err.println(jwt);

                CacheService cacheService = ApplicationHolder.getApplicationContext().getBean(CacheService.class);

                boolean b = cacheService.setNx(SystemParams.JWT_TOKEN_REDIS_PRE + uphone,jwt,3600 * 1000); // 向redis中存储token

                //我们自己定义一个规范,我们会将token放到响应头中返回
                response.addHeader("token", jwt);

            } else {
                bean.setCode("0");
                bean.setMessage("登陆失败，密码错误!");
            }
        } catch (Exception e) {
            bean.setCode("0");
            bean.setMessage("登陆失败，该手机号不存在!");
            return bean;
        }

        return bean;
    }

    // 注册
    @RequestMapping("/Register")
    public ResponseData Register(HttpServletResponse response, HttpServletRequest request) {

        ResponseData bean = new ResponseData();

        String busername = request.getParameter("username");

        // 获取请求的手机号
        String uphone = request.getParameter("uphone");
        // 获取请求的密码
        String password = request.getParameter("password");
        // 再次获取请求的密码
        String password2 = request.getParameter("password2");

        if (password.equals(password2)) {

            try {
                // 测试该手机号是否存在
                userService.selectByPrimaryKey(uphone).getUpassword();
                bean.setCode("2");
                bean.setMessage("该手机号码已注册!");
                return bean;
            } catch (Exception e) {
                Buser buser = new Buser();
                buser.setUusername(busername);
                buser.setUphone(uphone);
                buser.setUpassword(password);
                buser.setUstate(1); // 默认是激活状态
                buser.setUmoney(0); // 用户余额默认为0

                // 添加用户数据
                userService.insert(buser);

                bean.setCode("6");
                bean.setMessage("注册成功!");
                return bean;
            }
        }

        bean.setCode("4");
        bean.setMessage("两次密码输入不一致!");
        return bean;
    }

}
